<template>
  <el-card v-loading="loading">
    <el-table border style="margin-bottom: 10px" :data="skuArr">
      <el-table-column label="序号" type="index" align="center" width="80px" />
      <el-table-column label="名称" prop="skuName" show-overflow-tooltip wdith="150px" />
      <el-table-column label="描述" prop="skuDesc" show-overflow-tooltip wdith="150px" />
      <el-table-column label="默认图片" width="150px">
        <template #="{ row }">
          <el-image :src="row.skuDefaultImg" fit="cover" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="重量（g）" prop="weight" width="150px" />
      <el-table-column label="价格（元）" prop="price" width="150px" />
      <el-table-column label="操作" fixed="right" width="250px">
        <template #="{ row }">
          <el-button v-if="row.isSale === 1" type="success" icon="Top" size="small" title="上架" @click="saleSku(row)" />
          <el-button v-else type="primary" icon="Bottom" size="small" title="下架" @click="saleSku(row)" />
          <el-button type="warning" icon="Edit" size="small" title="编辑" @click="updateSku(row)" />
          <el-button type="info" icon="InfoFilled" size="small" title="查看详情" @click="openSkuDetail(row)" v-loading="row.skuDetailLoading" />
          <el-popconfirm :title="`是否确定删除该${row.skuName}吗？`" confirmButtonText="确定" cancelButtonText="取消" @confirm="deleteSku(row)">
            <template #reference>
              <el-button type="danger" icon="Delete" size="small" title="删除" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="pageNo"
      v-model:page-size="limit"
      :page-sizes="[10, 20, 30, 40]"
      layout="prev, pager, next, jumper, ->,sizes, total"
      @current-change="getHasSku"
      @size-change="sizeChange"
      :total="total"
      background
    />

    <!-- 查看商品详情 -->
    <skuDetail ref="skuDetailRef" />
  </el-card>
</template>

<script setup lang="ts">
  import { reqSkuList, reqSaleSku, reqCancelSaleSku, reqRemoveSku } from '@/api/product/sku'
  import type { SkuResponseData, SkuData } from '@/api/product/sku/types'
  import { getElMessage } from '@/utils/message'
  import { onMounted, ref } from 'vue'
  import skuDetail from './skuDetail.vue'

  const pageNo = ref<number>(1)
  const limit = ref<number>(10)
  const total = ref<number>(0)
  const loading = ref<boolean>(false)
  const skuArr = ref<SkuData[]>([])
  const skuDetailRef = ref<InstanceType<typeof skuDetail>>()
  onMounted(() => {
    getHasSku()
  })
  async function getHasSku(pager = 1) {
    try {
      loading.value = true
      pageNo.value = pager
      const res: SkuResponseData = await reqSkuList(pageNo.value, limit.value)
      if (res.code === 200) {
        skuArr.value = res.data.records.map((o) => {
          return {
            ...o,
            skuDetailLoading: false,
          }
        })
        total.value = res.data.total
      } else {
        getElMessage('获取sku列表失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      loading.value = false
    }
  }
  function sizeChange(pageSize: number) {
    limit.value = pageSize
    getHasSku()
  }

  // 上下架
  async function saleSku(row: SkuData) {
    try {
      const fn = row.isSale ? reqCancelSaleSku : reqSaleSku
      const res = await fn(row.id as number)
      if (res.code === 200) {
        getElMessage(row.isSale ? '下架成功' : '上架成功', 'success')
        getHasSku()
      } else {
        getElMessage(row.isSale ? '下架失败' : '上架失败', 'warning')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'danger')
    }
  }

  // 更新
  function updateSku(row: SkuData) {
    getElMessage(`程序员正在开发${row.skuName}中`, 'warning')
  }

  // 查看商品详情
  function openSkuDetail(row: SkuData) {
    skuDetailRef.value?.openDilog(row)
  }

  // 删除
  async function deleteSku(row: SkuData) {
    try {
      const res: any = await reqRemoveSku(row.id as number)
      if (res.code === 200) {
        getElMessage(`删除${row.skuName}成功`, 'success')
        getHasSku(skuArr.value.length ? pageNo.value : pageNo.value - 1)
      } else {
        getElMessage(`删除${row.skuName}失败`, 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    }
  }
</script>

<style lang="scss" scoped></style>
